package com.windaka.elements.config;


import com.windaka.elements.service.JdbcUserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * WebSecurityConfig
 * 配置了认证的方式、密码的加密方式
 * 配置了拦截的路由
 * 配置了注解EnableGlobalMethodSecurity 通过切面拦截
 * @author song
 * @date 9:49 下午 2021/11/7
 * @param
 * @return
 * @other
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private JdbcUserDetailsServiceImpl jdbcUserDetailsService;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 配置AuthenticationManagerBuilder
     * @author song
     * @date 3:35 下午 2021/11/16
     * @param
     * @return
     * @other
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // jdbcUserDetailsService 配置了用户账号密码认证方式
        // Bean为JdbcUserDetailsServiceImpl
        // 账号密码权限组装
        // passwordEncoder为加密器
        auth.userDetailsService(jdbcUserDetailsService).passwordEncoder(passwordEncoder);
    }

    /**
     * 路由拦截
     * @author song
     * @date 3:37 下午 2021/11/16
     * @param
     * @return
     * @other
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .permitAll()
                .and()
                .logout()
                .permitAll();
        http.httpBasic().disable();
    }

    /**
     * Bean AuthenticationManager
     * @author song
     * @date 2:24 下午 2021/11/16
     * @param
     * @return
     * @other
     **/
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
